I use jsViews to create a small form.
In the template I defined some buttons I bound to a custom handler.
Within the handler, I want to play with the event
object (especially, I want to prevent the default button behavior which is to submit the outer <form>
.
This works as expected with all browsers I tested except Firefox. the event object is undefined
with Firefox. All other browsers have a MouseEvent
object defined.
How to fix it using FF ?
Here is a small repro:
(function($) {
var dataVm = {
value: 42
};
var handlers = {
changeValue: function(valueToAdd) {
$.observable(dataVm).setProperty("value", dataVm.value + valueToAdd);
console.log(event); // Should not be undefined
}
};
$.templates("#mainTemplate").link("#container", dataVm, handlers);
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsviews/0.9.90/jsviews.min.js"></script>
<script id="mainTemplate" type="text/x-jsrender">
<input data-link="value" />
<button data-link="{on ~changeValue 1}">+1</button>
<button data-link="{on ~changeValue (-1)}">-1</button>
</script>
<div id="container">
</div>
PS: I use jQuery 1.12.4 and jsViews 0.9.90
In callback functions, you may inspect arguments and see what you need. In this case, we can try this inside changeValue callback:
(function($) {
var dataVm = {
value: 42
};
var handlers = {
changeValue: function(valueToAdd) {
$.observable(dataVm).setProperty("value", dataVm.value + valueToAdd);
console.log(arguments); // check what actual arguments are
}
};
$.templates("#mainTemplate").link("#container", dataVm, handlers);
})(jQuery);
And, you are now able to reach arguments[1] as event to execute preventDefault of that.
(function($) {
var dataVm = {
value: 42
};
var handlers = {
changeValue: function(valueToAdd) {
var theEvent = arguments[1];
$.observable(dataVm).setProperty("value", dataVm.value + valueToAdd);
console.log(arguments); // check what actual arguments are
theEvent.preventDefault(); // execute preventDefault from it
}
};
$.templates("#mainTemplate").link("#container", dataVm, handlers);
})(jQuery);