Как перенести функции в отдельный файл в MVVM?

0

Я следую за MVVM от Kendo UI. Здесь бизнес-функции записываются внутри viewModel Как мы можем переместить эти функции в другой файл?

Задача, с которой я сталкиваюсь, связана с ключевым словом "this" внутри этих функций, который ссылается на модель, присутствующую внутри наблюдаемого.

Просмотр модели

<script type="text/javascript">
    var viewModel = kendo.observable({

        // model definition
        employees: [
        { name: "Lijo", age: "28" },
        { name: "Binu", age: "33" },
        { name: "Kiran", age: "29" }
        ],

        personName: "",
        personAge: "",

        //Note: Business functions  does not access any DOM elements using jquery.
        //They are referring only the objects in the view model.

        //business functions  (uses "this" keyword - e.g. this.get("employees"))
        addEmployee: function () {
            this.get("employees").push({
                name: this.get("personName"),
                age: this.get("personAge")
            });

            this.set("personName", "");
            this.set("personAge", "");
        },

        deleteEmployee: function (e) {

            //person object is created using "e"
            var person = e.data;

            var employees = this.get("employees");
            var index = employees.indexOf(person);
            employees.splice(index, 1);
        }

    });

</script>

Глава

<head>
    <title>MVVM Test</title>

    <script type="text/javascript" src="lib/kendo/js/jquery.min.js"></script>
    <script type="text/javascript" src="lib/kendo/js/kendo.web.min.js"></script>

    <!----Kendo Template-->
    <script id="row-template" type="text/x-kendo-template">
          <tr>
                <td data-bind="text: name"></td>
                <td data-bind="text: age"></td>
                <td><button type="button" data-bind="click: deleteEmployee">Delete</button></td>
                <td>
          </tr>
    </script>


    <!--MVVM Wiring using Kendo Binding-->
    <script type="text/javascript">

        $(document).ready(function () {
            kendo.bind($("body"), viewModel);
        });

    </script>

</head>

тело

<body>
    <table>
        <thead>
            <tr>
                <th>
                    Name
                </th>
                <th>
                    Age
                </th>
            </tr>
        </thead>
        <!--The data-template attribute tells Kendo UI that the employees objects should be formatted using a Kendo UI template. -->
        <tbody data-template="row-template" data-bind="source: employees">
        </tbody>
    </table>
    <br />
    <br />
    <form>
    <input type="text" name="personName" placeholder="Name" data-bind="value: personName" /><br />
    <input type="text" name="personAge" placeholder="Age" data-bind="value: personAge" /><br />
    <button type="button" data-bind="click: addEmployee">
        Add</button>
    </form>
</body>

РЕКОМЕНДАЦИИ

  1. Kendo MVVM Framework - packtpub
  2. MVVM/Удаленное связывание - demos.telerik
  3. DropDownList/MVVM - demos.telerik
  4. Использование DataSource/Basic
Теги:
mvvm
kendo-ui

1 ответ

2

Независимо от того, определяете ли вы его в другом файле javascript или вне вашей функции kendo.observable, вам просто нужно связать "это" с функцией.

Это непроверено, но первое может работать, а второе обязательно работает!

 function externalAddEmployee() {
    this.get("employees").push({
           name: this.get("personName"),
           age: this.get("personAge")});
    this.set("personName", "");
    this.set("personAge", "");        
}

kendo.observable({
    // first solution: may not work because the 'this' you want is not properly defined
    addEmployee: externalAddEmployee.bind(this);
    // second solution: will work everytime
    // the 'this' is properly defined, just proxy the call to the function
    addEmployee: function() { return externalAddEmployee.apply(this, arguments); }

})

Чтобы улучшить второе решение, вы можете даже создать вспомогательную функцию:

function proxy(fn) { return function() { return fn.apply(this, arguments); })
// and then
kendo.observable({
    addEmployee: proxy(externalAddEmployee)
})

Ещё вопросы

Сообщество Overcoder
Наверх
Меню