将$ index和$ data作为参数传递给click处理程序的函数 [英] Passing $index and $data as arguments to function for click handler

查看:188
本文介绍了将$ index和$ data作为参数传递给click处理程序的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 $ index $ data 传递给 change_model 功能。该函数按以下顺序期望2个参数:(索引,数据)

I am passing $index and $data to the change_model function. The function is expecting 2 parameters in the following order: (index, data).

从viewModel我传递点击:$ root.change_model.bind($ data,$ index())。在函数 index 中打印 $ data ,并且 data 打印 index :价值相反。

From the viewModel I am passing click: $root.change_model.bind($data, $index()). Within the function index prints $data, and data prints index: values are reversed.

self.change_model = function(index, data) {
  self.patternSelectedIndex(index);
  selected_door = data.file;
  create_door();
};



<div data-bind="foreach: x.patterns">
    <div class="thumbnail" data-bind="css: { selected: $index() === $root.patternSelectedIndex() }">
      <img class='img model' style='width:164px;height:90px;padding:5px' data-bind="attr:{src:'images/models/' + $data.file + '.png'}, click: $root.change_model.bind($data, $index())" />
      <div class="caption">
        <span data-bind="text: $data.name"></span>
      </div>
    </div>
</div>


推荐答案

绑定的第一个参数将在您的函数中变为,因为Knockout仅使用常规的 bind 函数

The first argument of bind will become this inside your function, because Knockout is merely using the regular bind function.

你可以传递 $ data $ root 作为第一个(<$ c) $ c> thisArg )参数,或传递null或undefined,因为你似乎不需要它,因为你似乎使用 self = this 成语。

You can either pass $data or $root as the first (thisArg) argument, or pass null or undefined, as you don't really need it since you seem to use the self = this idiom.

例如:

var ViewModel = function () {
    var self = this;

    self.change_model = function (index, data) {
        console.log(this);
        console.log(index);
        console.log(data);
        // Actual code here
    };

    self.x = { patterns: [{ file: 'some-file', name: 'some-name' }] };
};

ko.applyBindings(new ViewModel());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div data-bind="foreach: x.patterns">
    <button data-bind="click: $root.change_model.bind($data, $index(), $data)">Click me!</button>
    <span data-bind="text: $data.name"></span>
</div>

这篇关于将$ index和$ data作为参数传递给click处理程序的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆