我有以下内容:
<div data-bind="liveEditor: PropertyNameINeed"></div>
如何使用jQuery获取名称“PropertyNameINeed”?
有没有比那个更好的解决方案? https://www.wimpyprogrammer.com/get-bound-property-name-in-a-knockoutjs-custom-binding/
感谢您的帮助。
答案 0 :(得分:0)
希望这对你有用,
Rails.application.config.assets.precompile = ['*.js', '*.css', '*.css.scss']
答案 1 :(得分:0)
我真的不明白为什么你需要这样做,但它仍然是一个有趣的问题需要解决。
我想到了一个解决方案,涉及“扩展”你感兴趣的绑定。你必须小心不要改变它的行为......
解释我的方法的最好方法是通过一个例子:
// In this example, I want to access all properties bound via a `text` binding.
// I want to be able to retreive information about the binding using a HTMLElement
// Here, we'll store our binding information
var textBinds = [];
// This function returns an object from the `textBinds` array
// based on a matching `element` property
var getTextBindingValueForElement = function(element) {
return textBinds.find(function(b) {
return b.element === element;
});
};
// For this example we're tapping in to the `text` binding. If you're only watching
// custom bindings, it might be better to call a helper function in their init
// Store a reference to knockout's original `text` binding's `init` method:
var og = ko.bindingHandlers.text.init;
// Extend the method:
ko.bindingHandlers.text.init = function(element, valueAccessor, allBindings, vm) {
// Loop through all of the viewmodel's properties to find the property
// that matches the current value.
// Note: if the value is a primitive (number, str, bool, null, etc.), this will
// return the first match. So it ONLY WORKS FOR OBJECTS/FUNCTIONS
var value = valueAccessor();
var prop = Object.keys(vm).find(function(key) {
return vm[key] === value;
});
// We're storing element, prop and value in a plain object
textBinds.push({
element: element,
prop: prop,
value: value
});
// This ensures the old behavior still works
return og.apply(this, arguments);
};
// Now, we can access the bound `text` property via the element inside an
// ordinary jQuery click listener
$(".js-onClick").click(function() {
var bindData = getTextBindingValueForElement(this);
console.log("Prop: " + bindData.prop);
console.log("Val: " + bindData.value());
});
ko.applyBindings({
testLabel: ko.observable("Hello world")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="js-onClick" data-bind="text: testLabel"></div>
这种方法的优点:
value
)。我真的不明白为什么你需要财产名称...... 限制: