Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observe non-ember globals

Tags:

ember.js

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:function(){
    //some functionality
}.property('localStorage.someKey')

Is it possible to do what I'm trying to do directly?

like image 924
kcgolden Avatar asked Jan 12 '13 04:01

kcgolden


1 Answers

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.

like image 110
Yehuda Katz Avatar answered Sep 24 '22 02:09

Yehuda Katz