简体   繁体   English

Ember.js +把手自定义助手

[英]Ember.js + Handlebars custom helper

I'm trying to implement a simple conditional statement in Handlebars that changes based on an attribute in my controller. 我试图在Handlebars中实现一个简单的条件语句,该条件语句根据控制器中的属性而变化。

I've managed to come up with; 我设法解决了;

Handlebars.registerHelper("businessVerificationState", function(state, block) {
  var value = Ember.getPath(this, "state");
  if (value == state) {
    return block(this);
  }
});

App.businessController.business refers to a model object I've created and "state" is an attribute. App.businessController.business指的是我创建的模型对象,“状态”是一个属性。 Below is the template. 以下是模板。

<script type="text/x-handlebars">
  {{#with App.businessController.business}}
    {{#exampleState "test1"}}
      <p>Test 1</p>
    {{/exampleState}}

    {{#exampleState "test2"}}
      <p>Test 2</p>
    {{/exampleState}}
 </script>

This all works swell. 这一切工作膨胀。 Except when my model attributes changes. 除非我的模型属性发生更改。 From the console in webkit .. if I type .. 从webkit的控制台中..如果我键入..

business.set("state", "test2"); business.set(“ state”,“ test2”); for example - nothing changes. 例如-没有任何变化。

If I use other standard handlebar statements like IF or UNLESS - the content changes based on when I update model attributes. 如果我使用诸如IF或UNLESS之类的其他标准车把语句-内容将根据我更新模型属性的时间而变化。

Obviously I'm doing something incredibly wrong and would appreciate any help. 显然,我正在做一些令人难以置信的错误,希望对您有所帮助。

The easiest way to do this is to have a parent view that has a property bound to the controller value and child views that have the state names specified as a property. 最简单的方法是让一个父视图具有绑定到控制器值的属性,而子视图具有指定为属性的状态名称。 You can then define an isVisible computed property which will automatically toggle visibility of the child view depending on if it matches the current value bound in the parent view. 然后,您可以定义一个isVisible计算属性,该属性将根据子视图是否与父视图中绑定的当前值匹配来自动切换子视图的可见性。

Your template could look like: 您的模板可能如下所示:

<script type="text/x-handlebars">
  {{#view Ember.View currentStateBinding="App.businessController.business.state"}}
    {{#view App.StateView stateName="test1"}}
      <p>Test 1</p>
    {{/view}}

    {{#view App.StateView stateName="test2"}}
      <p>Test 2</p>
    {{/view}}
  {{/view}}
</script>

And your JS code: 和你的JS代码:

var App = Ember.Application.create();

App.businessController = Ember.Object.create({
    business: Ember.Object.create({
        state: 'test1'
    })
});

App.StateView = Ember.View.extend({
    isVisible: function() {
        return this.get('stateName') === this.getPath('parentView.currentState');
    }.property('parentView.currentState')
});

Here's a working jsFiddle example: http://jsfiddle.net/ebryn/QAxPU/ 这是一个工作的jsFiddle示例: http : //jsfiddle.net/ebryn/QAxPU/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM