i need to pass variable "blabla" of resize event to stop event how can i do this?
thanks by advance here a part of the code to explain what i need:
.resizable({
disabled: disablePoignee,
handles: poignees,
resize: function (e, ui) {
var blabla = "pioup";
},
stop:function(e,ui){
//try to get blabla
}});
thanks by advance for your help
CodePudding user response:
In this code...
.resizable({
disabled: disablePoignee,
handles: poignees,
resize: function (e, ui) {
var blabla = "pioup";
},
stop: function(e,ui) {
//try to get blabla
}});
... variable blabla
is only available inside the function passed (as resize
property of options
object) into resizable
plugin function. This value is encapsulate - essentially hidden - from the rest of the world.
To 'unhide' it, you have two options. First, make this variable external to scope of both resize
and stop
functions:
var blabla; // or const, or let
// ...
.resizable({
resize: function (e, ui) {
blabla = "pioup"; // note that `var` shouldn't be used here, as existing variable is reused
},
stop: function(e, ui) {
doSomethingWith(blabla);
}});
That, however, won't work if there's more than one instance of resizable
created in your code, and each of those should use its own value of blabla
. In this case it might be useful to go with the second option - and assign some custom property to the jQuery object hosting the plugin:
.resizable({
resize: function (e, ui) {
ui.originalElement.data('blabla', 'someValue');
},
stop: function(e, ui) {
doSomethingWith(ui.originalElement.data('blabla'));
}});
Benefit of this approach is that data stays attached to this object even when the plugin is destroyed.
CodePudding user response:
Consider the following example.
$(function() {
$("#resizable").resizable({
resize: function(e, ui) {
$(this).data("foo", "bar-" $(this).width());
},
stop: function(e, ui) {
console.log($(this).data("foo"));
}
});
});
#resizable {
width: 150px;
height: 150px;
padding: 0.5em;
}
#resizable h3 {
text-align: center;
margin: 0;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="resizable" class="ui-widget-content">
<h3 class="ui-widget-header">Resizable</h3>
</div>
Instead of creating a more global variable, you can use jQuery Data.
Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.
With this, we can Set and Get data for each element. If you only have one resizable element, this is not a big deal. If you have many resizable items, this is very helpful in consolidating your script.