0

双向数据绑定的人为示例

var user = {
    model: function(name) {
        this.name = m.prop(name);
    },
    controller: function() {
        return {user: new user.model("John Doe")};
    },
    view: function(controller) {
        m.render("body", [
            m("input", {onchange: m.withAttr("value", controller.user.name), value: controller.user.name()})
        ]);
    }
};

https://lhorie.github.io/mithril/mithril.withAttr.html


我试过上面的代码不起作用。

它是第一个尝试附加以下内容的。

m.mount(document.body, user);

未捕获的 SyntaxError:意外的令牌 n


然后我尝试附加以下内容。

var users = m.prop([]);
var error = m.prop("");
m.request({method: "GET", url: "/users/index.php"})
        .then(users, error); 

▼/users/index.php

<?php
echo '[{name: "John"}, {name: "Mary"}]';

未捕获的 SyntaxError:意外的令牌 n


如何操作 m.withAttr 教程代码?

4

2 回答 2

1

尝试m('body', [...])从您的控制器返回。

view: function (ctrl) {
    return m("body", [
        ...
    ]);
}

render不应在 Mithril 组件内部使用(render仅用于在现有 DOM 节点上安装 Mithril 组件)。

于 2015-07-06T01:05:37.203 回答
0

该示例难以操作,因为它是人为设计的,并不是开箱即用的。这是一个稍作修改的工作版本:

http://jsfiddle.net/ciscoheat/8dwenn02/2/

var user = {
    model: function(name) {
        this.name = m.prop(name);
    },
    controller: function() {
        return {user: new user.model("John Doe")};
    },
    view: function(controller) {
        return [
            m("input", {
                oninput: m.withAttr("value", controller.user.name),
                value: controller.user.name()
            }),
            m("h1", controller.user.name())
        ];
    }
};

m.mount(document.body, user);

所做的更改:

  1. m.mount在指定为第一个参数的元素中注入 html ,因此其中渲染body元素view将使主体在主体中。
  2. 将输入字段事件更改oninput为即时反馈,并添加了一个h1显示模型,因此您可以在输入字段更改时看到它的变化。

使用 m.request

另一个示例如何根据您的修改发出显示检索到的数据的 ajax 请求:

http://jsfiddle.net/ciscoheat/3senfh9c/

var userList = {
    controller: function() {
        var users = m.prop([]); 
        var error = m.prop("");

        m.request({
            method: "GET", 
            url: "http://jsonplaceholder.typicode.com/users",
        }).then(users, error);

        return { users: users, error: error };
    },
    view: function(controller) {
        return [
            controller.users().map(function(u) {
                return m("div", u.name)
            }),
            controller.error() ? m(".error", {style: "color:red"}, "Error: " +  controller.error()) : null
        ];
    }
};

m.mount(document.body, userList);

如果请求的url 没有返回有效的 JSON,则可能会发生Unexpected token n/users/index.php错误,因此您需要修复 JSON 数据以使其与您自己的代码一起使用。name该字段周围没有引号。

于 2015-07-06T12:16:44.267 回答