将模型绑定到模板的控件

Bind a model to a template's controls

本文关键字:控件 模型 绑定      更新时间:2023-09-26

我正在尝试将模型绑定到余烬中的模板控件,但没有成功。首先,我尝试创建模型,然后将模型绑定到控件。我正在使用命令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. 

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

例如

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')
});

控制器

 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>

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

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

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

然后我们需要将控制器更改为对象控制器,如下所示:

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

使用对象控制器时,属性会自动绑定到模型的属性。 例如,汽车模型的品牌属性将绑定到汽车控制器的品牌属性,因此您只需将字段绑定到模板中的这些属性,如下所示:

{{input value=brand }}

希望对您有所帮助!