Observe non-ember globals

前端 未结 1 640
闹比i
闹比i 2021-02-08 04:13

I want a computed property to observe a non-ember global: a specific key in localStorage. Is this possible? The following does not seem to cut it:

someProperty:f         


        
相关标签:
1条回答
  • 2021-02-08 04:49

    In general, you can observe regular JavaScript objects just fine. You just need to use Ember.get and Ember.set to modify them:

    var pojo = {};
    
    var MyObject = Ember.Object.extend({
      bigEyeballs: function() {
        var O_O = this.get('pojo.O_O');
        if (O_O) { return O_O.toUpperCase(); }
      }.property('pojo.O_O')
    });
    
    var obj = MyObject.create({ pojo: pojo });
    console.log(obj.get('bigEyeballs'));
    
    Ember.set(pojo, 'O_O', "wat");
    console.log(obj.get('bigEyeballs'));
    

    You can see this working in this JSBin.

    Local Storage is a bit of a different matter, as it's not really a normal JavaScript object. You can create a small Ember wrapper around local storage, and use that for observation:

    var LocalStorage = Ember.Object.extend({
      unknownProperty: function(key) {
        return localStorage[key];
      },
    
      setUnknownProperty: function(key, value) {
        localStorage[key] = value;
        this.notifyPropertyChange(key);
        return value;
      }
    });
    
    var storage = new LocalStorage();
    
    var MyObject = Ember.Object.extend({
      bigEyeballs: function() {
        var O_O = this.get('pojo.O_O');
        if (O_O) { return O_O.toUpperCase(); }
      }.property('pojo.O_O')
    });
    
    var obj = MyObject.create({ pojo: storage });
    
    console.log(obj.get('bigEyeballs'));
    
    Ember.set(storage, 'O_O', "wat");
    console.log(obj.get('bigEyeballs'));
    

    You can see this live on JSBin.

    In both cases, the important thing is that you will have to use Ember-aware setting and getting in order to observe these properties.

    0 讨论(0)
提交回复
热议问题