简体   繁体   中英

Get instance to call method?

I'm currently trying to set the value of a colorpicker. I'm using this color picker: http://mjolnic.github.io/bootstrap-colorpicker/

The colorpicker is bound to a html element with jquery:

$('.sample-selector').colorpicker({ /*options...*/ });

It also has a few methods like:

.setColor(value)

How can i get the colorpicker instance so i can call a method?

I tried a lot of things. First i init colorpicker:

$('#thecolor').colorpicker();

This works. But i can't seem to find a way to call a method:

$('#thecolor').colorpicker.toRGB()
$('#thecolor').toRGB()
$('#thecolor').colorpicker().toRGB()

and so on. It must but something really small :)

To get the colorpicker instance from the DOM:

var cp = $('#thecolor').data().colorpicker;

The color object is a property:

cp.color.toRGB();

From the bootstrap-colorpicker doc, you can call toRGB like this:

$('#thecolor').colorpicker().on('changeColor', function(ev){
    console.log(ev.color.toRGB());
});

I think you've missed this line:

Color object methods

Each triggered events have a color object used internally by the picker. This object has several useful methods.

Look at the following example:

$('.my-colorpicker-control').colorpicker().on('changeColor', function(ev){
    bodyStyle.backgroundColor = ev.color.toHex();
});

So it's not available from the outside. You can try to hack around that (not tested)

$('.my-colorpicker-control').colorpicker().on('create', function(ev) {
    window.mycolorpicker = ev.color;
});

if (window.mycolorpicker) {
    window.mycolorpicker.setColor('...');
}

Good luck!

Try this:

var colorPicker = $("#thecolor").colorpicker();
$(colorPicker).toRGB(); // object method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM