Skip to content

Commit 1383538

Browse files
committed
also expose the raw JS object for Sortable, and automatically destroy it when it goes out of scope
1 parent 0bf6e0a commit 1383538

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

src/lib.rs

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,14 @@ mod js {
1717

1818
#[wasm_bindgen(module = "/sortable.esm.js")]
1919
extern "C" {
20+
#[wasm_bindgen(extends = js_sys::Object)]
2021
pub type Sortable;
2122

2223
#[wasm_bindgen(constructor)]
2324
pub fn new(elt: &web_sys::Element, opts: &js_sys::Object) -> Sortable;
25+
26+
#[wasm_bindgen(method)]
27+
pub fn destroy(item: &Sortable);
2428
}
2529
}
2630

@@ -226,19 +230,36 @@ impl Options {
226230
/// long as you want the callbacks to be callable, as JS code will error out
227231
/// should an event happen after it was dropped.
228232
pub fn apply(&self, elt: &web_sys::Element) -> Sortable {
229-
js::Sortable::new(elt, &self.options);
233+
let sortable = js::Sortable::new(elt, &self.options);
234+
let object_ref: &js_sys::Object = sortable.as_ref();
235+
let raw_object = object_ref.clone();
230236
Sortable {
237+
raw_object,
238+
sortable,
231239
_callbacks: self.callbacks.clone(),
232240
}
233241
}
234242
}
235243

236244
/// Data related to the Sortable instance
237245
///
238-
/// It must be kept alive on the rust sideas long as the instance can call
239-
/// callbacks, as otherwise the link between the js-side callback and the
240-
/// rust-side callback would be lost.
246+
/// When it is dropped, the list is made non-sortable again. This is required
247+
/// because callbacks could be called otherwise. If it is a problem for you, you
248+
/// can leak it, but be aware of the fact that it is a leak.
241249
pub struct Sortable {
250+
/// Raw Sortable JS object, should this crate not expose the necessary
251+
/// methods
252+
pub raw_object: js_sys::Object,
253+
254+
/// raw_object but with the proper type
255+
sortable: js::Sortable,
256+
242257
/// Keep the callbacks alive
243258
_callbacks: [Option<Rc<Closure<dyn FnMut(js_sys::Object)>>>; CallbackId::_Total as usize],
244259
}
260+
261+
impl Drop for Sortable {
262+
fn drop(&mut self) {
263+
self.sortable.destroy();
264+
}
265+
}

0 commit comments

Comments
 (0)