DWQA QuestionsCategory: ProgramThe easy to use route hashchange is similar history.js thinking
tcdona asked 1 month ago

Do something similarhttps://github.com/jgallen23/routieSingle page app
It needs to deal with the forward, backward and view routes
http://millermedeiros.github.io/crossroads.js/
https://github.com/asual/jquery-address
https://github.com/cowboy/jquery-bbqI haven’t updated it for a long time
https://github.com/browserstate/history.jsIt’s a complicated feeling
I remember that a project I did a few years ago was implemented by monitoring hash. Now I meet this requirement again
After a search, we found that it was the previous library [crossroads, BBQ], history.js Actually, more than 2000 lines don’t support opera 11 and mercury IOS
I would like to ask you how to recommend some useful routes, and why there is no relatively clear and easy-to-use solution for such a complicated front-end URL monitoring after so many years
Do you have to force me to copy onehttps://github.com/RubyLouvre/mmRouter/Is that right
[every time I encounter such a solution problem, I find that situ Da’s things are still very practical ~ ~]

Bubukou replied 1 month ago

You don’t need so much code to listen to hash, do you? Visual inspection within 20 lines

Bubukou replied 1 month ago

history.js What the hell is 2K doing?

2 Answers
Bubukou answered 1 month ago

Why don’t you try mine?
Q. JS is a lightweight front-end single page routing framework.

Lightweight, fast, minimalist

https://github.com/itorr/q.js
In order to make better use of cache and less back-end support, q.js abandons HTML5 state and reproduces the URL routing function through #! Format URL HACH.

  1. No JavaScript library, can be used with
  2. Source code less than 100 lines after compression834byte
  3. Support IE6 + chrome Safari FF
  4. If the situation is not determined, the use of q.js is bound to registerwindow.Q

Of all thingsdiebeginning
Let’s start with a simple hello world

html<!DOCTYPE html>
<meta charset="UTF-8">



<div id="m"></div>



<script src="q.js"></script>


<script>
Q.reg('home',function(){
    document.getElementById('m').innerHTML='Hallo World';
});

Q.init({
    Index: 'home' / * home page address*/
});
</script>

After opening the example, the browser willhttp://simple.com/Jump tohttp://simple.com/#!homeAnd the halo world is displayed on the page.
So, your first passQ.jsThe implementation of URL routing works~
Then we will explain in detail how to make theQ.jsWorking.
Registration URL
stayQ.jsIt provides two ways to register URL: keyword and regular expression.
Keyword registration URL inQ.jsIn the case of the former can not meet the needs, we can use the regular registration method~

Using regular expressions to register URLs may increase the running time in varying degrees (it is not obvious). If allowed, please give priority to using keywords to register URLs~

Next, we plan a blog URL to learn how to use itQ.jsRegister URL.
home page
Let’s start with the home page~
Before registration, let’s analyze the requirements of the registration homepage URL:
1. First of all, the home page has a fixed format
2. In most cases, it is not necessary to reflect parameter passing in URL
3. It is the default display page when opening the domain name
First, we register a fixed pagehome, callback does not expect to pass value

javascriptQ.reg('home',function(){
    console.log ('home page opened ');
    /*Javascript code*/
});

Access through the above code#!homeThe following callbacks are triggered.
In the callback, we modify the dom of the page to change the content without refreshing.
(this part is not in the scope of this document)
In this way, similarly, we can also achieve similar#!about, links#!friendAnd so on page registration.
After realizing the URL registration of the home page, we need to jump to thehomePage.
Q.jsStart up of, byQ.initFunction implementation. =

javascriptQ.init({
    Index: 'home' / * if the home page address cannot be accessed, it will also jump back to this page*/
});

Add the index parameter to the init startup parameter, so that when we visit the page, it will be opened by default#!home
If you think#!homeIn!Not in line with expectations, this It can also be changed~

javascriptQ.init({
    key:'^_ ^The segmentation symbol between # and URL name in '/ * URL is exclamation mark by default*/
    Index: 'home' / * the home page address is not accessible, and the path will also jump back to this address*/
});

It can be split by any string conforming to the URI specification, or even set to null.

When set to null, modern search engines such as Google may not be able to index by routing address. Please set it carefully

Article page and flipping
The article page and the home page are not the same, only part of the URL is the same, we need to distinguish different article pages through different parts of the URL, not the default page.

  1. The article page has a fixed format
  2. The unique ID of the article needs to be reflected in the URL

Q.jsIn keyword mode, the parameters are connected by/Split, please plan the URL according to the order

javascriptQ.reg('article',function(aid){
    if(!aid)
        Return alert ('the incoming parameter is incorrect. Please confirm the address you visited. ');

    console.log ('the article is opened, and its unique ID is' + aid ');
    /*Javascript code*/
});

Visit the page after registration#!article/123It will triggerarticlePage callback, and pass in parameter 1"123"

Q. JS does not judge the type of incoming data, so be sure to confirm the data format in the callback

Turn the page, but the way to transfer the value is basically the same. I won’t repeat it here
Category page
In fact, the category page is very similar to the article page, but the parameter one becomes the category name. When there is more content, the current page number needs to be passed

  1. The category page has a fixed format
  2. The unique name of the category needs to be reflected in the URL
  3. There may be page information

According to the above requirements, we still use the keyword registration mode to register acategoryThe URL of the default two parameter classification unique namecstr, pagepage

javascriptQ.reg('category',function(cstr,page){
    if(!cid)
        Return alert ('the incoming parameter is incorrect. Please confirm the address you visited. ');

    If (! Page) / * if*/
        page=1;

    console.log ('the classification page is opened, and the classification name is' + CSTR ');
    console.log ('current page: '+ page));

    /*Here's the pseudo code iTorr.js  For reference only*/
    /*Ajax request based on category unique name and page number*/
    $.x('/api/category/'+cstr+'/page/'+page,function(d){
        console.log(d);
        /*Modify the dom of the page here*/
    });
});

visit#!category/photoWill be introducedphotoreachcategoryCallback function for
visit#!category/photo/2Will be introducedphotoand2reachcategoryCallback function for
When parameter 2 does not exist, it needs to be processed in the callback function~
Navigation bar
With these URLs, we need a navigation bar to provide access between pages,
The navigation bar needs to modify the navigation bar style every time the page changes to indicate the currently open page.
Our html is like this

html<nav>
    The home page</a>
    About</a>
    < a http://www.youthfriend.com > links</a>
</nav>

CSS is generally like this

CSSnav{line-height:2em;}
nav a{display:inline-block;vertical-align:top;padding:0 .5em;}
nav a.active{background:#369;color:#FFF;}

At this time, we need to dynamically modify the URL in nav through JavaScript every time the URL changesactive classTo modify the style.

javascript/*This pseudo code is based on iTorr.js  For reference only*/
Var navchange = function (L) {/ * pop callback will be triggered every time the URL changes*/
    /*L is the name of the current callback function (currently only keyword callback is supported)*/

    Var a; // temporary variable
    If (a = $('nav a.active ') // if the DOM exists 
        a. Classname = '; // modify its classname
    If (a = $('nav a [#! '+ L +'] ') // if this DOM exists 
        a. Classname ='active '; // modify its classname
};

Q.jsProvidedQ.popEvent, which can be registered byQ.popThe implementation calls back every time the URL changes,Q.popEvent does not conflict with other URL events and runs before other URL callback functions. Please pay attention to the trigger time.
Registration and modificationQ.popThere are many ways. It can be registered in the startup function, for example:

javascriptQ.init({
    /*... various other parameters*/
    pop:navchange // Register pop function
});

You can also register by keyword

javascriptQ.reg('pop',navchange);

It can even be modified directlyQ.pop

javascriptQ.pop=navchange

Please note that usingQ.jsPlease avoid usingQ.jsKeep the keyword as the URL address
Reserved keywords include:reg,pop,go,V
Here, our simple blog can almost be used~

There is still a regular registration URL left. Regular registration is determined before keyword determination. No matter before or after registration, please pay attention to the determination order. Therefore, because of this, the keyword part of our keyword determination can be replaced by the regular expression registration method.

But if we still want to use reserved keywords, we can use regular registration method

javascriptQ.reg(/pop/,function(){
    console.log ('pop event ');
});

The regular registration method needs to specify the values that may be passed in in the regular register
Above our blog URL planning has been basically completed~
How to realize richer URL format
Although the keyword registration method is convenient, it only supports the format of keyword / parameter 1 / parameter 2 / parameter 3. If you want to realize more unscientific URL format, you can use the regular registration method~
For example, if the link of a video website starts with a V followed by a digital ID, it is expected that there will be a parameter one and it is a number

javascriptQ.reg(/v(\d+)/,function(vid){
    console.log ('pop event parameter 1: '+ VID));
});

Visit like thishttp://simple.com/#!v1234567The value is passed1234567Give the callback function.
I want to know which page to implement in JavaScript?
visitQ.lashVariable to return the current page keyword

Q. Currently, last can only return the URL of keyword registration, and regular support is expected to be added in the next version update.

How to jump to a specific link through JavaScript
Because inQ.jsYes! Keywords can be modified. If URL jump is realized through JavaScript, it can be calledq.gofunction

JavaScriptQ.go('category/code');

Of course, in most cases, we recommend using the HTML native a tag link to jump through visitors

HTMLCode classification</a>

above.

tcdona replied 1 month ago

Only when the code style adapts to it can we find that it is loop monitoring, and the interface is not the expected express style.Generally speaking, I think it’s very good [stable, compatible, simple and easy to use] accounts for the top two, but it’s not the answer I particularly want.

Bubukou replied 1 month ago

If onhashchange (line 9) can’t be used, it will be monitored in a loop.Want to know what kind of framework is easy to use oaq?

Red leaves dancing in autumn answered 1 month ago

It seems that we can’t add the splicing URL.
For example, there are multiple classifications.
catgory1=a catgory2=b catgory3=c
Can it be like this?
view?catgory1=a&catgory2=b&catgory3=c