1

假设我有一张地图:

map = new can.Map({foo: 'bar'})

我想绑定foo另一个地图中的值。我可以:

otherMap = new can.Map({fizzle: map.compute('foo')})

但这并不符合我的预期。

  1. 我希望otherMap.attr('fizzle')返回bar,但它返回一个函数。我不得不打电话otherMap.attr('fizzle')()
  2. 我希望能够通过调用来更改值otherMap.attr('fizzle', 'moo'),但这不会更改计算值。相反,如果我想更改基础值,我必须调用otherMap.attr('fizzle')('moo').

有没有办法使用计算值创建一个映射,其行为类似于普通属性?

谢谢!

4

1 回答 1

1

I would recommend using the define plugin which makes it easy to create computed getters and setters without having to explicitly create computes. In your example like this:

var map = new can.Map({
    foo: 'bar',
    baz: 'bla'
});

var OtherMap = can.Map.extend({
    define: {
        fizzle: {
            get: function() {
                return map.attr('foo') + '/' + map.attr('baz');
            },
            set: function(value) {
                map.attr('foo', value);
            }
        }
    } });

var other = new OtherMap();

console.log(other.attr('fizzle'));

other.attr('fizzle', 'something');
console.log(map.attr('foo'));

Demo in this Fiddle.

于 2014-09-18T20:45:02.383 回答