【问题标题】:How to make this data binding in Ember component embedded in a view work?如何使嵌入在视图中的 Ember 组件中的数据绑定起作用?
【发布时间】:2014-06-04 18:15:25
【问题描述】:

我有一个视图,其中嵌入了一个组件。我想使用 {{view}} 帮助器将参数传递给视图,然后让组件也使用该数据,但它似乎不起作用。我不知道我错过了什么......

代码如下:

App.DisplayView = Ember.View.extend({
    templateName: 'display',
    property1: 'property1 default value',
    property2: 0,

    debugProps : function() {
        console.log('view property1: ' + this.get('property1'));
        console.log('view property2: ' + this.get('property2'));
    }.on('init')

});


App.DisplayEmbeddedComponent = Ember.Component.extend({
    prop1: 'prop1 default value',
    prop2: 0,

    actions : {
        buttonClicked: function() {
            console.log('button clicked!');
            console.log('prop1: ' + this.get('prop1'));
            console.log('prop2: ' + this.get('prop2'));
        }
    },

    debugProps : function() {
        console.log('this: ' + this);
        console.log('prop1: ' + this.get('prop1'));
        console.log('prop2: ' + this.get('prop2'));
    }.on('init')

});

模板如下:

<script type="text/x-handlebars" data-template-name="display">
    <h2>Dislay view</h2>
    {{display-embedded prop1=property1 prop2=property2 }}
</script>

<script type="text/x-handlebars" data-template-name="components/display-embedded">
    {{input value=prop1 type="text"}}
    {{input value=prop2 type="text"}}

    <button {{action "buttonClicked"}}>Button X</button>
</script>

然后我使用具有嵌入式组件的视图,如下所示:

{{view App.DisplayView property1='prop 1 value' property2='prop 2 value'}}

输出如下:

// this shows data has been passed to the view correctly
view property1: prop 1 value
view property2: prop 2 value

// this shows that "this" points to component as expected, but properties remain null
this: <App.DisplayEmbeddedComponent:ember526>
prop1: undefined
prop2: undefined

// same when I click the button in the component: properties are undefined
button clicked!
prop1: undefined
prop2: undefined 

如您所见,prop1prop2 似乎未定义,输入以空值开头,而不是我传递给视图的值。

我做错了什么?我试图正确理解这种嵌套,但似乎没有文档涵盖这种组件嵌入视图的情况。

谢谢!

【问题讨论】:

    标签: javascript model-view-controller ember.js


    【解决方案1】:

    视图中定义的属性需要使用视图来引用。

    {{display-embedded prop1=view.property1 prop2=view.property2 }}
    

    http://emberjs.jsbin.com/cahogawa/1/edit

    【讨论】:

    • 感谢您拯救了这一天。您是否知道有任何文件指出我可能遗漏了这一点?
    • 它真的有效吗,我去测试并传递给组件没有用,它在范围内有效(我在添加答案时最初测试的内容),但后来我创建了一个组件并没有通过,emberjs.jsbin.com/cahogawa/2/edit
    • 成功了。您的小提琴中的问题是您的组件传递了参数jack 而不是blah。看看这个! emberjs.jsbin.com/cahogawa/6/edit
    • 大声笑,我喜欢做傻事,5个小时的睡眠是不够的;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 2015-11-10
    • 1970-01-01
    • 2014-07-24
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多