[英]ember properties and javascript chaining
Looking at the ember.js documentation ( http://emberjs.com/guides/object-model/computed-properties/ ) I understand how to use properties, but hadn't run across chained methods in an object declaration before. 查看ember.js文档( http://emberjs.com/guides/object-model/computed-properties/ ),我了解如何使用属性,但是以前没有在对象声明中跨链方法运行。
It looks to me like the property
method should get called immediately, but this doesn't seem to be the case. 在我看来,应该立即调用
property
方法,但是事实并非如此。
Person = Ember.Object.extend({
// these will be supplied by `create`
firstName: null,
lastName: null,
fullName: function() {
var firstName = this.get('firstName');
var lastName = this.get('lastName');
return firstName + ' ' + lastName;
}.property('firstName', 'lastName')
});
var tom = Person.create({
firstName: "Tom",
lastName: "Dale"
});
tom.get('fullName') // "Tom Dale"
If I make a small js snippet, nothing here seems to do anything. 如果我制作一个小的js代码段,那么这里似乎什么也做不了。 http://jsfiddle.net/xXStr/
http://jsfiddle.net/xXStr/
var a = {
what: function() {
alert ("oh yeah");
},
bar: function() {
alert ("bar");
return this;
}.what()
}
a.bar();
How do chained methods in an object declaration work? 对象声明中的链接方法如何工作?
If you look inside the Ember source , you will find that the Function
prototype is extended to include a property
method. 如果查看Ember源代码 ,则会发现
Function
原型已扩展为包含property
方法。
Function.prototype.property = function() {
var ret = Ember.computed(this);
return ret.property.apply(ret, arguments);
};
Looking deeper , we see that Ember.computed
returns an instance of Ember.Computed
. 更深层次看 ,我们看到
Ember.computed
返回的实例Ember.Computed
。
Ember.computed = function(func) {
var args;
if (arguments.length > 1) {
args = a_slice.call(arguments, 0, -1);
func = a_slice.call(arguments, -1)[0];
}
var cp = new ComputedProperty(func);
if (args) {
cp.property.apply(cp, args);
}
return cp;
};
// ...
function ComputedProperty(func, opts) {
this.func = func;
this._cacheable = (opts && opts.cacheable !== undefined) ? opts.cacheable : true;
this._dependentKeys = opts && opts.dependentKeys;
}
Ember.ComputedProperty = ComputedProperty;
Thus, whenever you write 因此,每当你写
foo: function() {
return this.get('bar')
}.property('bar')
you are actually creating an anonymous function and then immediately invoking its property
method, returning an instance of Ember.ComputedProperty
. 您实际上是在创建一个匿名函数,然后立即调用其
property
方法,并返回一个Ember.ComputedProperty
实例。 This is what gets assigned to the foo
property. 这就是分配给
foo
属性的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.