gpt4 book ai didi

javascript - 将模型绑定(bind)到模板的控件

转载 作者:行者123 更新时间:2023-12-03 11:12:41 25 4
gpt4 key购买 nike

我试图将模型绑定(bind)到 ember 中的模板控件,但没有成功。首先,我尝试创建模型,然后将模型绑定(bind)到控件。我正在使用命令 var newCar = sapp.Car.create(); 创建一辆汽车。但我收到错误

EmberError: You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set. 

我的问题是如何创建模型并将其绑定(bind)到模板的控件?下面是我如何实现它的代码示例

例如

window.sapp = Ember.Application.create();
sapp.Router.map(function() {
this.route("cars");
});
sapp.Car = DS.Model.extend({
plateNumber: DS.attr('string'),
color: DS.attr('string'),
brand: DS.attr('string')
});

Controller

 sapp.CarsController = Ember.Controller.extend({
var newCar = sapp.Car.create();
//getting error while creating car
//error:mberError: You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.
});

模板

 <script type="text/x-handlebars" data-template-name="cars">
<h1>Add Car</h1>
<table>
<tr>
<td>Plate Number</td>
<td>
{{ input value=newCar.plateNumber }}
</td>
</tr>
<tr>
<td>Color</td>
<td>
{{ input value=newCar.color }}
</td>
</tr>
<tr>
<td>Brand</td>
<td>
{{ input value=newCar.brand }}
</td>
</tr>
<tr style="text-align:right">
<td colspan="2">
<button>Add Car</button>
</td>
</tr>
</table>
</script>

最佳答案

首先,您应该在路由模型 Hook 中设置模型。正如错误消息所示,您应该使用商店的 createRecord 函数来创建模型的新实例。

sapp.CarsRoute.extend(function() {
model: function() {
return this.store.createRecord('car');
}
});

这将自动确保在转换到汽车路线之前设置汽车记录,并在汽车 Controller 上设置模型属性。

然后我们需要将 Controller 更改为 ObjectController,如下所示:

sapp.CarsController = Ember.ObjectController.extend({});

使用对象 Controller ,属性会自动绑定(bind)到模型的属性。例如,您的汽车模型的品牌属性将绑定(bind)到您的汽车 Controller 的品牌属性,因此您可以在模板中将字段绑定(bind)到这些属性,如下所示:

{{input value=brand }}

希望有帮助!

关于javascript - 将模型绑定(bind)到模板的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27497195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com