how to save a filter in Dojo

我只是一个虾纸丫 提交于 2019-12-05 15:51:34
Bucket

Right off the bat, here are the two three approaches I see:

Store the filter in a URL (Okay)

Simply get the window.location and parse out the query string using dojo/io-query::queryToObject():

require(['dojo/io-query'], function (ioQuery) {
    var uri = window.location.href;
    var query = uri.substring(uri.indexOf("?") + 1, uri.length);
    query = ioQuery.queryToObject(query);
});

(Documentation for dojo/io-query)


Store the filter in a cookie (Better)

The dojo/cookie module makes this very, very easy:

require(['dojo/cookie', 'dojo/json'], function (cookie, json) {
    var filter = { ... };
    cookie("myFilter", json.stringify(filter)); //store the cookie
    // json.parse(cookie("myFilter")); 
    // ^-- returns the cookie as a JS object
});

(Documentation for dojo/cookie)

Obviously, the user must have cookies enabled for this to work, but it's much cleaner than storing a bunch of variables in a URL for them to bookmark.


Use HTML5 Local Storage as suggested by Dimitri M: (Even better)

Check to see if the user's agent supports Local Storage, and if so, use that global variable to hold on to the filter:

require(['dojo/json'], function(json) {
    function supportsLocalStorage() {
        return ('localStorage' in window) && window['localStorage'] !== null;
    }

    var filter = { ... };

    if(supportsLocalStorage()) {
        localStorage.setItem("myFilter", json.stringify(filter));
    }

    // json.parse(localStorage.getItem("myFilter")) 
    // ^-- returns the filter as a JS object
});

An advantage in using web storage is that you can store much more data than cookies can.

You could conceivably use cookies as a fallback for browsers that don't support Local Storage, (i.e. when supportsLocalStorage() returns false) at the cost of adding a touch more overhead to your design, so ultimately it's your call, depending on what browsers you want to support.

Browser Compatibility for Web Storage

How about cookies?

The grid widget has a cookie plugin(link), but id doesn't save the filter. Maybe extending the plugin or the grid could be an option.

Passing the filter properties as string also sounds like an option. Knowing the conditions, and the values that can be used, or their type, you can easily validate the filter before applying it to the grid.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!