mardi 23 février 2016

What's a good way to create event listeners, so that I can listen to changes in javascript classes?

I am trying to create an MV* pattern in javascript. I have a Model class, a View class, and a Collection class.

http://ift.tt/1QwEM3I

Example Model: So for example I have a set method. If this is called and a new attribute is made somewhere here I need to announce to other parts of the code a change on this model happens.

// Model
var Model = function(model) {
  this.attributes = model; // attributes becomes the object passed in
  this.change = false; // by default set change to false
}
Model.prototype.set = function(object) {
  var key = Object.keys(object)[0]; // get first object key
  this.attributes[key] = object[key]; // set the attribute based on object value
  this.change = true; // trigger(announce) a change
  return this.attributes; // return new attributes
}
Model.prototype.get = function(attribute) {
  return this.attributes[attribute]; // return desired attribute
};

Example View: Below is a View class where I will pass the model into it.

// View
var View = function(object) {
  var self = this;
  this.object = object; // set this object to be the object argument passed in to the constructor 
  this.element = document.querySelector(object.element); // grab the DOM element desited
  this.model = object.model; // set this model to be the model passed into the constructor
  if(object.inititalize) {
    object.initialize.call(this); // initialize the view
  }
};

View.prototype.render = function() {
  this.object.render.call(this); // call render when needed
}

Implementation of the above: Here I instantiate the classes, inside the constructor for the Model I am passing in an object which will become the attributes of the Model. Then in the constructor for the View I am defining the view by passing an object to the constructor. Inside this object I also define the Model

// Implementation
var player = new Model({name: 'mike'}); // model instance

var testView = new View({
  element: '.testEl',
  model: player,
  render: function() {

    alert('rendered'); // feedback

    var self = this;
    this.element.innerHTML = this.model.get('name');

    // artificially change the model
    setTimeout(function() {
      self.model.set({
        name: 'Billy'
      });
    }, 5000);

  }
}); // view instance


var Start = function() {
  testView.render();
};

Start();

My Question: Now that the View has a model how can I structure this code so that I can add event listeners? When there is a change on the model in this example model.set() is called and it should announce a change, or publish a change and whatever is subscribed to that should be aware of it.

Aucun commentaire:

Enregistrer un commentaire