面向对象的Javascript与纯jQuery和.data存储 [英] Object Oriented Javascript vs. Pure jQuery and .data storage

查看:58
本文介绍了面向对象的Javascript与纯jQuery和.data存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前的编程风格是使用John Resig的Class.extend函数的OO javascript: http ://ejohn.org/blog/simple-javascript-inheritance/

My current style of programming is OO javascript using the Class.extend function by John Resig: http://ejohn.org/blog/simple-javascript-inheritance/

这一切都没问题,但我发现自己写的是很多只有getter的getter和getter用于init。此外,当将这些对象的实例存储在一个数组中供以后使用时,似乎会导致IE中的内存泄漏。

This has been fine but I find myself writing numerous setters and getters that only get used on init. Also, it seems to lead to memory leaks in IE when storing instances of these objects in an array for later use.

我开始偏爱更小,更清洁等等看似过度的OO方法的可读代码。我的想法是现在使用jquery并使用.data方法存储数据属性,将所有内容都放在dom之外。例如,您只需使用类推文向dom添加div,而不是创建新的Tweet对象的实例,只需在.data缓存中添加诸如author,timestamp,reply to,sent from等属性。那个dom元素。

I am starting to favor smaller, cleaner, and more readable code over the seemingly overkill OO approach. My idea is to now just base everything off the dom using jquery and storing data properties using the .data method. For example, instead of creating an instance of a new Tweet object, you would simply add a div to the dom with class tweet and simply add the properties like author, timestamp, reply to, sent from, etc. in the .data cache for that dom element.

在创建像twitter这样的流中的项目等事物时,您如何看待这种结构较少的方法? OO和原型继承是最好的方法还是更严格的dom操作?

What do you think of this less structured approach when creating instances of things such as items in a stream like twitter? Is OO and prototypal inheritance the best approach or is strict dom manipulation better?

推荐答案

我正在做类似的事情。我采用了OO javascript方法。但我没有使用数组,而是使用键值对象。 是唯一的dom元素id,是对象本身。它看起来像这样。

I am doing something similar. I took the OO javascript approach. But instead of using arrays i use a key value object. The key is a unique dom element id, the value is the object itself. it looks something like this.

例如:

var collection = {};
var $domEl = jQuery;              // jquery dom element
var myClass= new MyClass($domEl); // class instance

// add to collection
collection[$domEl.attr('id')] = myClass;

// remove
delete collection[$domEl.attr('id')];

确实取决于对象的复杂程度。严格的.data方法需要依赖所有相关方法的插件,然后将数据存储在元素数据中。我有许多方法与严格的元素交互无关,所以我将方法和数据保存在类中。

Really it depends on the complexity of your objects. A strictly .data approach would need to rely on plugins for all of the related methods, and then store data in the elements data. I have many methods that are not related to strictly element interaction, so i keep the methods and data in the class.

这篇关于面向对象的Javascript与纯jQuery和.data存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆