0

How can I access View's element that related to Model's object?

For example, I have a collection of Products. Each product has color property. I'd like to "hide" (i.e. remove View representation) every product whose color equals to "red".

The only way I know so far is through invoking (for examle) destroy() method of Model's object (the code below). But I don't want to destroy Model's object. Is it possible to remove View's element without changing its Model?

// App
hide_red_products: function() { 
  Product.each(function(x) {
    if (x.attributes.color == "red") { x.destroy() }
  })
}


// Products' view
initialize: function() {
  this.model.bind('destroy', this.remove_element, this);
}

remove_element: function() {
  return $(this.el).remove();
}

1 Answer 1

2

The model should not control what the view is doing.

You should use the trigger method to trigger an event. Assuming the color changes from some color to red, you should use the change event. If you listen to the change event, you shouldn't even need the hide_red_products method.

// App
hide_red_products: function() { 
  Product.each(function(x) {

    //if (x.attributes.color == "red") { x.trigger() }
    // you should never access a models attributes using the attributes key
    if (x.get('color') === 'red') { x.trigger('change'); } // shouldn't actually need this.
  })
}


// Products' view
initialize: function() {
  //this.model.bind('destroy', this.remove_element, this);
  this.model.bind('change', this.remove_element, this);
}

remove_element: function(model) {
  if (model.get('color') === 'red') {
     $(this.el).remove();
  }
}

Like I said earlier, you shouldn't have to call a method to remove the element if the view listens to change events. If you feel it's necessary you can trigger it yourself using change or a custom event x.trigger('changedToRed');

Sign up to request clarification or add additional context in comments.

2 Comments

Beat me by a couple minutes. I whipped up a quick'n'dirty (and contrived) demo if you want it: jsfiddle.net/ambiguous/Ex8KJ/1
Thank yous very much for the answer and demo app, very useful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.