ilteris
ilteris

Reputation: 457

computed property that changes its value with action in Ember.js

I do have a controller that has an action {{loadRight}} that passes the current model to the controller when I click a button.

When I first load the app, I also use firstElement computed property which pulls the first element from my model array.

Basically what I want to do is create a second computed property which would return the current model that's clicked so that I can use this information in my template.

I created a currentElement computed property however since I suck at javascript I couldn't pass the current model from action method to the computed property. I keep getting model is not defined error.

I would appreciate any help. Below is my controller.

// controller works.js
import Ember from "ember";

export default Ember.Controller.extend({
  firstElement: function () {
    return this.get('model.firstObject');
  }.property('model.[]'),


  currentElement: function () {
    if(!currentModel) {
      currentModel = this.get('model.firstObject');
    }
    return currentModel;
  }.property('model.[]'),


  actions: {
    loadRight: function (currentElement) {
    console.log(currentElement);
    }

  }});

Upvotes: 0

Views: 1464

Answers (1)

artych
artych

Reputation: 3669

You could define property selectedElement (that's clicked). When loadRight fired you could set selectedElement with selection. Then currentElement is simple computed property, depends on model.firstObject and selectedElement.

export default Ember.Controller.extend({
  firstElement: function () {
    return this.get('model.firstObject');
  }.property('model.[]'),

  selectedElement: null,

  currentElement: function () {
    return (this.get('selectedElement') || this.get(`firstElement`));
  }.property('firstElement', 'selectedElement'),

  actions: {
    loadRight: function (selection) {
      this.set('selectedElement', selection);
      return false; // or something transition logic 
    }
  }
});

Upvotes: 1

Related Questions