应用$use
方法.selector
后将被缓存。
HTML:
<div data-container>
<div data-something>smthng</div>
</div>
JS:
var View = Backbone.View.extend({
el : '[data-container]',
ui : {
something : '[data-something]'
},
someFn : function () {
this.$use(this.ui.something).css('background', '#999');
return this;
},
$use : function (selector) {
console.log(typeof this.ui[selector] === 'undefined' ? 'dom query' : 'already cached');
var $selector = this.ui[selector] === selector ?
this.ui[selector] :
this.$(selector);
return this.ui[selector] = $selector;
}
});
new View().someFn().someFn().someFn();
演示:http: //jsfiddle.net/vpetrychuk/K7nmr/